<?php 
class User extends CI_Model{
	
	public $id;
	public $first_name;
	public $last_name;
	public $email;
	public $last_login;
	public $full_name;
	
	public function authenticateUser($user, $password){
		
		$password = sha1($password);
		//$data['password'] = $password;
		$result = get_instance()->db->query('SELECT * FROM user WHERE email = ? ', 	array($user))->row();	
		$data['debug']=$result;
		if ($result) {
			if ($result->password == $password){
				 $current = $this->mapArrayToUser($result);
				 $data['message'] = 'success';
				 $current->logSelfIn();
			}
			else $data['message'] = 'Wrong password';
		}
		else $data['message'] = 'No such user';
		echo json_encode($data);
		
		
	}
	
	private function logSelfIn(){
			get_instance()->session->set_userdata('current_user', $this->id);
			$this->updateTimeStamp();
	}

	public function getCurrentUser(){
		$sess = get_instance()->session->userdata('current_user');
		if (is_null($sess)) return null;
		$user =  $this->getUserByID($sess);
		if (!is_null($user)) return $user;
		return null;
	}

	public function logSelfOut(){
		get_instance()->session->set_userdata('current_user',null);
	}
	
	public function updateTimeStamp(){
		get_instance()->db->query('UPDATE user SET last_login = DEFAULT WHERE id = ?', array($this->id));	
		
	}
	
	public function getUserByID($id){
		sanitizeID($id);
		$row = get_instance()->db->query('SELECT id, first_name, last_name, email, last_login FROM user WHERE id =?', array($id))->row();
		if (is_null($row)) return null;
		$result = $this->mapArrayToUser($row);	
		
		return $result;		
	}
	
	private function mapArrayToUser($object){
		$vars = get_object_vars($object);
		$user = new User();
		foreach($vars as $key=>$value){
			$user->$key=$value;
		}
		$user->full_name = $user->first_name . " ". $user->last_name;
		return $user;
	}
	
	public function getVotedForPetition($petition_id){
		$row = get_instance()->db->query("SELECT * FROM petition_vote WHERE user_id = ? AND petition_id = ?",
			 array($this->id, $petition_id))->row();

		
		return $row;
	}
}